var IMAGE_BASE_URL="http://localhost:9999/pic"; //上传图片路径
var FILE_BASE_URL="http://localhost:9999/file";    //上传文件路径
var IMAGE_BASE_PATH="E:\\auelog\\images"; //上传图片路径
var FILE_BASE_PATH="E:\\auelog\\file";    //上传文件路径

Date.prototype.format = function(format){ 
    var o =  { 
    "M+" : this.getMonth()+1, //month 
    "d+" : this.getDate(), //day 
    "h+" : this.getHours(), //hour 
    "m+" : this.getMinutes(), //minute 
    "s+" : this.getSeconds(), //second 
    "q+" : Math.floor((this.getMonth()+3)/3), //quarter 
    "S" : this.getMilliseconds() //millisecond 
    };
    if(/(y+)/.test(format)){ 
    	format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
    for(var k in o)  { 
	    if(new RegExp("("+ k +")").test(format)){ 
	    	format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
	    } 
    } 
    return format; 
};

var row = 1;  //定义row，用于编辑商品传递数据

var editor; //编辑器使用

var TT = TAOTAO = {
	// 编辑器参数
	kingEditorParams : {
		//指定上传文件参数名称
		filePostName  : "uploadFile",
		//指定上传文件请求的url。
		uploadJson : '/pic/upload',
		//上传类型，分别为image、flash、media、file
		dir : "image"
	},
	// 格式化时间
	formatDateTime : function(val,row){
		var now = new Date(val);
    	return now.format("yyyy-MM-dd hh:mm:ss");
	},
	// 格式化连接
	formatUrl : function(val,row){
		if(val){
			return "<a href='"+val+"' target='_blank'>查看</a>";			
		}
		return "";
	},
	// 格式化价格
	formatPrice : function(val,row){
		return (val/1000).toFixed(2);
	},
	// 格式化商品的状态
	formatItemStatus : function formatStatus(val,row){
        if (val == 1){
            return '正常';
        } else if(val == 2){
        	return '<span style="color:red;">下架</span>';
        } else {
        	return '未知';
        }
    },
    
    init : function(data){
    	// 初始化图片上传组件
    	this.initPicUpload(data);
    	// 初始化选择类目组件
    	this.initItemCat(data);
    },
    // 初始化图片上传组件
    initPicUpload : function(data){
    	$(".picFileUpload").each(function(i,e){
    		var _ele = $(e);
    		_ele.siblings("div.pics").remove();
    		_ele.after('\
    			<div class="pics">\
        			<ul name="pics_ul_name"></ul>\
        		</div>');
    		// 回显图片
        	if(data && data.pics){
        		var imgs = data.pics.split(",");
        		for(var i in imgs){
        			if($.trim(imgs[i]).length > 0){
        				console.log("回显图片路径==="+imgs[i]);
//        				var url = imgs[i].substring(imgs[i].indexOf(IMAGE_BASE_PATH)+IMAGE_BASE_PATH.length);
//        				console.log("回显图片路径url==="+url);
        				var url = IMAGE_BASE_URL+imgs[i];
        				console.log("回显图片路径拼接url==="+url);
        				_ele.siblings(".pics").find("ul").append("<li><a href='"+url+"' target='_blank'><img src='"+url+"' width='80' height='50' /></a></li>");
        				console.log('回显图片_ele.siblings(".pics").find("ul")==='+_ele.siblings(".pics").find("ul").attr('name'));
//        				alert("<a href='"+url+"' target='_blank'>科室间江诗丹顿就<img src='"+url+"' width='80' height='50' /></a>");
//        				_ele.siblings(".pics").find("ul").append("<li>hahha</li>");
//        				var form = $(this).parentsUntil("form").parent("form");
//        				_ele.find(".pics ul").append("<li><a href='"+url+"' target='_blank'><img src='"+url+"' width='80' height='50' /></a></li>");
        			}
        		}
        	}
        	//给“上传图片按钮”绑定click事件
        	$(e).click(function(){
        		var form = $(this).parentsUntil("form").parent("form");
        		//打开图片上传窗口
        		KindEditor.editor(TT.kingEditorParams).loadPlugin('multiimage',function(){
        			var editor = this;
        			editor.plugin.multiImageDialog({
						clickFn : function(urlList) {
							var imgArray = [];
							KindEditor.each(urlList, function(i, data) {
								imgArray.push(data.url);
//								form.find(".pics ul").append("<li><a href='"+data.url+"' target='_blank'><img src='"+data.url+"' width='80' height='50' /></a></li>");
								var url = data.url.substring(data.url.indexOf(IMAGE_BASE_PATH)+IMAGE_BASE_PATH.length);
								var step = i+1;
								form.find(".pics ul").append("<li><a href='"+IMAGE_BASE_URL+url+"' target='_blank'><img src='"+IMAGE_BASE_URL+url+"' width='80' height='50' /></a></li>");
								if(form.attr("id") == "itemAddForm"){
									console.log("~~~~进入itemAddForm上传图片==="+form.attr("id"));
									form.append('<input type="hidden" name="imageUrl'+step+'" value="'+url+'"/>');
								}
								if(form.attr("id") == "itemBrandAddForm"){
									console.log("~~~~进入itemBrandAddForm上传图片==="+form.attr("id"));
									form.find("[name=logo]").val(url);
								}
//								if(form.attr("id") == "itemCatForm"){
//									console.log("~~~~进入itemCatForm上传图片==="+form.attr("id"));
//									form.find("[name=menu_image]").val(url);
//								}
								console.log("logo的数量------"+form.find("[name=logo]").length);
								console.log("itemBrandAddForm的数量------"+form.find("[name=itemBrandAddForm]").length);
								console.log("form.attr(id)------"+form.attr("id"));
								console.log("上传图片路径==="+url);
								console.log("上传图片路径IMAGE_BASE_URL+url==="+IMAGE_BASE_URL+url);
								console.log("上传图片名==="+"imageUrl"+step);
//								console.log("上传图片名==="+"i"+i);
							});
							form.find("[name=image]").val(imgArray.join(","));
							editor.hideDialog();
						}
					});
        		});
        	});
    	});
    	
    	$(".picFileUploadBrand").each(function(i,e){
    		var _ele = $(e);
    		_ele.siblings("div.pics").remove();
    		_ele.after('\
    			<div class="pics">\
        			<ul></ul>\
        		</div>');
    		// 回显图片
        	if(data && data.pics){
        		var imgs = data.pics.split(",");
        		for(var i in imgs){
        			if($.trim(imgs[i]).length > 0){
        				console.log("回显品牌图片路径==="+imgs[i]);
        				var url = IMAGE_BASE_URL+imgs[i];
        				console.log("回显品牌图片路径拼接url==="+url);
        				_ele.siblings(".pics").find("ul").append("<li><a href='"+url+"' target='_blank'><img src='"+url+"' width='80' height='50' /></a></li>");
        			}
        		}
        	}
        	//给“上传图片按钮”绑定click事件
        	$(e).click(function(){
        		var form = $(this).parentsUntil("form").parent("form");
        		//打开图片上传窗口
        		KindEditor.editor(TT.kingEditorParams).loadPlugin('multiimage',function(){
        			var editor = this;
        			editor.plugin.multiImageDialog({
						clickFn : function(urlList) {
							var imgArray = [];
							KindEditor.each(urlList, function(i, data) {
								imgArray.push(data.url);
								var url = data.url.substring(data.url.indexOf(IMAGE_BASE_PATH)+IMAGE_BASE_PATH.length);
								if(form.attr("id") == "itemBrandAddForm"){
									console.log("~~~~进入上传图片==="+form.attr("id"));
									form.find(".pics ul").append("<li><a href='"+IMAGE_BASE_URL+url+"' target='_blank'><img src='"+IMAGE_BASE_URL+url+"' width='80' height='50' /></a></li>");
									form.find("[name=brandImg]").val(url);
								}
//								console.log("logo的数量------"+form.find("[name=logo]").length);
//								console.log("itemBrandAddForm的数量------"+form.find("[name=itemBrandAddForm]").length);
//								console.log("form.attr(id)------"+form.attr("id"));
								console.log("上传品牌图片路径==="+url);
								console.log("上传品牌图片路径IMAGE_BASE_URL+url==="+IMAGE_BASE_URL+url);
							});
							form.find("[name=image]").val(imgArray.join(","));
							editor.hideDialog();
						}
					});
        		});
        	});
    	});
    },
    
    /**
     * 初始化选择类目组件
     * @param i 索引index
     * @param e element - 当前的元素（也可使用 "this" 选择器）
     */
    initItemCat : function(data){
    	$(".selectItemCat").each(function(i,e){
    		var _ele = $(e);
    		if(data && data.cid){
    			_ele.after("<span style='margin-left:10px;'>"+data.cid+"</span>");
    		}else{
    			_ele.after("<span style='margin-left:10px;'></span>");
    		}
    		_ele.unbind('click').click(function(){
    			$("<div>").css({padding:"5px"}).html("<ul>")
    			.window({
    				width:'500',
    			    height:"450",
    			    modal:true,
    			    closed:true,
    			    iconCls:'icon-save',
    			    title:'选择类目',
    			    onOpen : function(){
    			    	var _win = this;
    			    	$("ul",_win).tree({
    			    		url:'/item/v1/cat/list',
    			    		animate:true,
    			    		onClick : function(node){
    			    			if($(this).tree("isLeaf",node.target)){
    			    				// 填写到cid中
    			    				_ele.parent().find("[name=categoryId]").val(node.id);
    			    				console.log("node.id====="+node.id);
    			    				_ele.next().text(node.text).attr("categoryId",node.id);
    			    				$(_win).window('close');
    			    				if(data && data.fun){
    			    					data.fun.call(this,node);
    			    				}
    			    			}
    			    		}
    			    	});
    			    },
    			    onClose : function(){
    			    	$(this).window("destroy");
    			    }
    			}).window('open');
    		});
    	});
    },
    
    createEditor : function(select){
    	return KindEditor.create(select, TT.kingEditorParams);
    },
    
    /**
     * 创建一个窗口，关闭窗口后销毁该窗口对象。<br/>
     * 
     * 默认：<br/>
     * width : 80% <br/>
     * height : 80% <br/>
     * title : (空字符串) <br/>
     * 
     * 参数：<br/>
     * width : <br/>
     * height : <br/>
     * title : <br/>
     * url : 必填参数 <br/>
     * onLoad : function 加载完窗口内容后执行<br/>
     * 
     * 
     */
    createWindow : function(params){
    	$("<div>").css({padding:"5px"}).window({
    		width : params.width?params.width:"80%",
    		height : params.height?params.height:"80%",
    		modal:true,
    		title : params.title?params.title:" ",
    		href : params.url,
		    onClose : function(){
		    	$(this).window("destroy");
		    },
		    onLoad : function(){
		    	if(params.onLoad){
		    		params.onLoad.call(this);
		    	}
		    }
    	}).window("open");
    },
    
    closeCurrentWindow : function(){
    	$(".panel-tool-close").click();
    },
    
    changeItemParam : function(node,formId){
    	/*$.getJSON("/item/v1/param/query/itemcatid/" + node.id,function(data){
			  if(data.status == 200 && data.data){
				 $("#"+formId+" .params").show();
				 var paramData = JSON.parse(data.data.paramData);
				 var html = "<ul>";
				 for(var i in paramData){
					 var pd = paramData[i];
					 html+="<li><table>";
					 html+="<tr><td colspan=\"2\" class=\"group\">"+pd.group+"</td></tr>";
					 
					 for(var j in pd.params){
						 var ps = pd.params[j];
						 html+="<tr><td class=\"param\"><span>"+ps+"</span>: </td><td><input autocomplete=\"off\" type=\"text\"/></td></tr>";
					 }
					 
					 html+="</li></table>";
				 }
				 html+= "</ul>";
				 $("#"+formId+" .params td").eq(1).html(html);
			  }else{
				 $("#"+formId+" .params").hide();
				 $("#"+formId+" .params td").eq(1).empty();
			  }
		  });*/
    },
    getSelectionsIds : function (select){
    	var list = $(select);
    	var sels = list.datagrid("getSelections");
    	var ids = [];
    	for(var i in sels){
    		ids.push(sels[i].id);
    	}
    	ids = ids.join(",");
    	return ids;
    },
    
    /**
     * 初始化单图片上传组件 <br/>
     * 选择器为：.onePicUpload <br/>
     * 上传完成后会设置input内容以及在input后面追加<img> 
     */
    initOnePicUpload : function(){
    	$(".onePicUpload").click(function(){
			var _self = $(this);
			KindEditor.editor(TT.kingEditorParams).loadPlugin('image', function() {
				this.plugin.imageDialog({
					showRemote : false,
					clickFn : function(url, title, width, height, border, align) {
						var input = _self.siblings("input");
						input.parent().find("img").remove();
						input.val(url);
						input.after("<a href='"+url+"' target='_blank'><img src='"+url+"' width='80' height='50'/></a>");
						this.hideDialog();
					}
				});
			});
		});
    },
    
    /**
     * 在EasyUI Window中加载编辑器
     * @param windowID Window窗口的ID
     * @param EditerID 编辑器所在文本框的ID
     */
    createEditorOnEasyUIWindow : function(windowID,EditerID){
        $('#'+windowID).window({
            onOpen : function(){
                editor = KindEditor.create('#'+EditerID, {
                    resizeType : 1,
                    allowPreviewEmoticons : false,
                    allowImageUpload : false,
                    minWidth : 500,
                    items : [
								'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
								'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
								'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
								'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
								'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
								'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
								'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
								'anchor', 'link', 'unlink', '|', 'about'                        
							]
                });
            },
            onBeforeClose: function () {
                // 关闭window前移除编辑器
                   KindEditor.remove('#'+EditerID);
            }
        });
    },
    
    /**
     * 输出编辑器内容
     */
    outputEditer : function(){
    	editor.sync();
    }
};

/**
 * 查询扩展属性列表
 */
function selectExtendAttrList(categoryId,usageMode){
	var params = {
			categoryId : categoryId,
			usageMode : usageMode
		};
	$.ajax({
		type:"post",
		contentType:"application/json; charset=utf-8",
		url:path+'/item/v1/param/selectattr?page=1&rows=10000',
		data:JSON.stringify(params),
		dataType:"json",
		success:function(data){
			if(data.result == 1){
				console.log("获取属性列表成功");
			}
		}
   });
}
